﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PPAP.BO;
using System.Data;

namespace PPAP.Web.Part
{
    public partial class PPARHistory : PageBase
    {
        PPARBO bo = new PPARBO();
        PPARBO ppbo = new PPARBO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //dgList.DataSource = bo.GetListForSupplierDecided(CurrentUser.UnitName).Tables[0];
                //dgList.DataBind();

                DataSet ds = null;
                if (CurrentUser.UnitId == "0")
                    ds = ppbo.GetPlantListForPlantID(CurrentUser.UnitName);
                else
                    ds= ppbo.GetPlantListForSupplierid(CurrentUser.UnitId == "99" ? CurrentUser.Id : null);
                ddlPlant.Items.Add(new ListItem("All", "All"));
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        ddlPlant.Items.Add(new ListItem(dr["plantname"].ToString(), dr["id"].ToString()));
                    }
                }
                else
                {
                    ddlPlant.Items.Add(new ListItem("Not added plant information", "0"));
                }
                if (CurrentUser.UnitId == "0" || CurrentUser.UnitId == "99")  //供应商点操作，跳转到SupplierPPARWeb页面
                {
                    dgList.Columns[9].Visible = false;
                    dgList.Columns[20].Visible = false;

                    ddlStatus.Items.Add(new ListItem("All", "All"));
                    ddlStatus.Items.Add(new ListItem("Un-allocated", "-1"));
                    ddlStatus.Items.Add(new ListItem("Allocated", "0"));
                    ddlStatus.Items.Add(new ListItem("Created", "1"));
                    ddlStatus.Items.Add(new ListItem("Submitted", "2"));
                    ddlStatus.Items.Add(new ListItem("Ready for sampling", "3"));
                    ddlStatus.Items.Add(new ListItem("Not ready for sampling", "4"));
                    ddlStatus.Items.Add(new ListItem("Decided", "7"));
                }
                else //后台用户点操作，跳转到CreatPPAPWeb页面
                {
                    dgList.Columns[10].Visible = false;
                    dgList.Columns[19].Visible = false;

                    ddlStatus.Items.Add(new ListItem("All", "All"));
                    ddlStatus.Items.Add(new ListItem("Un-allocated", "-1"));
                    ddlStatus.Items.Add(new ListItem("Allocated", "0"));
                    ddlStatus.Items.Add(new ListItem("Created", "1"));
                    ddlStatus.Items.Add(new ListItem("Submitted", "2"));
                    ddlStatus.Items.Add(new ListItem("Ready for sampling", "3"));
                    ddlStatus.Items.Add(new ListItem("Not ready for sampling", "4"));
                    ddlStatus.Items.Add(new ListItem("Circulating", "5"));
                    ddlStatus.Items.Add(new ListItem("Released", "6"));
                    ddlStatus.Items.Add(new ListItem("Decided", "7"));
                }
                btnSubmit_Click(null, null);
            }
        }

        //状态显示

        public string ShowAuditStatus(string Status, string FINALSTATUS, string isinapp)
        {
            string result = "";
            result = "<span style='color:red'>已提交</span>";

            switch (Status.ToLower())
            {
                case "0":
                    if (isinapp == "0")
                        result = "<span style='color:red'>Un-allocated</span>";
                    else
                        result = "<span style='color:blue'>Allocated</span>";
                    break;
                case "1":
                    result = "<span style='color:red'>Created</span>";
                    break;
                case "2":
                    result = "<span style='color:red'>Submitted</span>";
                    break;
                case "3":
                    result = "<span style='color:red'>Ready for sampling</span>";
                    break;
                case "4":
                    result = "<span style='color:red'>Not ready for sampling</span>";
                    break;
                case "5":
                    result = "<span style='color:red'>Circulating</span>";
                    break;
                case "6":
                    if (FINALSTATUS == "0")
                        result = "<span style='color:red'>Circulating</span>";
                    else if (FINALSTATUS == "4")
                        result = "<span style='color:red'>Circulating</span><span style='color:red'>(Reject)</span>";
                    else if (FINALSTATUS == "5" || FINALSTATUS == "8")
                        result = "<span style='color:blue'>Released</span><span style='color:red'>(Reject)</span>";
                    else
                        result = "<span style='color:blue'>Released</span>";
                    break;
                case "7":
                    if (FINALSTATUS == "8")
                        result = "<span style='color:red'>Decided</span><span style='color:red'>(Reject)</span>";
                    else
                        result = "<span style='color:blue'>Decided</span>";
                    break;

                default:
                    result = "<span style='color:red'></span>";
                    break;
            }
            return result;
        }

        public string ShowAuditStatus2(string Status, string isinapp)  //供应商看到的状态与后台用户看到的状态不同
        {
            string result = "";
            result = "<span style='color:red'>已提交</span>";

            switch (Status.ToLower())
            {
                case "0":
                    if (isinapp == "0")
                        result = "<span style='color:red'>Un-allocated</span>";
                    else
                        result = "<span style='color:blue'>Allocated</span>";
                    break;
                case "1":
                    result = "<span style='color:red'>Created</span>";
                    break;
                case "2":
                    result = "<span style='color:red'>Submitted</span>";
                    break;
                case "3":
                    result = "<span style='color:red'>Ready for sampling</span>";
                    break;
                case "4":
                    result = "<span style='color:red'>Not ready for sampling</span>";
                    break;
                case "5":
                    result = "<span style='color:red'>Ready for sampling</span>";
                    break;
                case "6":
                    result = "<span style='color:red'>Ready for sampling</span>";
                    break;
                case "7":
                    result = "<span style='color:blue'>Decided</span>";
                    break;

                default:
                    result = "<span style='color:red'></span>";
                    break;
            }
            return result;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = GetDataSet("");// bo.GetListForWhere(txtPartno.Text, ddlPlant.SelectedItem.Text, cbAll.Checked, CurrentUser.UnitId == "0" ? CurrentUser.UnitName : null);
                AspNetPager2.RecordCount = ds.Tables[0].Rows.Count;
                dgList.DataSource = GetPageTable(ds.Tables[0], AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
                dgList.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        private DataSet GetDataSet(string sort)
        {
            string sqlwhere = "";
            if (!cbAll.Checked)
            {
                //if (txtPartno.Text.Trim().Contains("*"))
                //    sqlwhere += "   and bdntpartno like '%" + txtPartno.Text.Trim().Replace("*", "") + "%'";
                //else
                    if (txtPartno.Text.Trim() != "")
                        sqlwhere += "   and lower(bdntpartno) like lower('%" + txtPartno.Text.Trim() + "%') ";
                if (ddlPlant.SelectedValue != "All")
                    sqlwhere += "   and lower(p.plantname) like lower('%" + ddlPlant.SelectedItem.Text + "%') ";
                if (txtPartName.Text.Trim() != "")
                    sqlwhere += " and lower(bdntpartname) like lower('%" + txtPartName.Text.Trim() + "%') ";
                if (ddlStatus.SelectedValue != "All")
                {
                    if ((CurrentUser.UnitId == "0" || CurrentUser.UnitId == "99") && ddlStatus.SelectedValue == "3") //供应商
                        sqlwhere += " and (a.status=3 or a.status=5 or a.status=6) ";
                    else
                    {
                        if (ddlStatus.SelectedValue == "5")
                            sqlwhere += "  and( a.status=5 or (a.status=6 and (a.FINALSTATUS=0 or a.FINALSTATUS=4))) ";
                        else if (ddlStatus.SelectedValue == "6")
                            sqlwhere += " and a.status=6 and  a.FINALSTATUS!=0 and  a.FINALSTATUS!=4 ";
                        else if (ddlStatus.SelectedValue == "-1")
                            sqlwhere += " and a.status=0 and a.isinapp=0 ";
                        else if (ddlStatus.SelectedValue == "0")
                            sqlwhere += " and a.status=0 and a.isinapp=1 ";
                        else
                            sqlwhere += " and a.status=" + ddlStatus.SelectedValue;
                    }

                }
                if (tbVersion.Text.Trim() != "")
                    sqlwhere += " and lower(bdntrevisionno) like lower('%" + tbVersion.Text.Trim() + "%') ";
                if (DatePicker1.Text.Trim() != "")
                    sqlwhere += " and trunc(a.ppardate)>=to_date( '" + DatePicker1.Text.Trim() + "', 'yyyy-mm-dd ') ";
                if (DatePicker2.Text.Trim() != "")
                    sqlwhere += " and trunc(a.ppardate)<=to_date( '" + DatePicker2.Text.Trim() + "', 'yyyy-mm-dd ') ";
                if (My1.Text.Trim() != "")
                    sqlwhere += " and trunc((select min(starttime)  from samplecard  where pparid=a.id and status<>9))>=to_date( '" + My1.Text.Trim() + "', 'yyyy-mm-dd ') ";
                if (My2.Text.Trim() != "")
                    sqlwhere += " and trunc((select min(starttime)  from samplecard  where pparid=a.id and status<>9))<=to_date( '" + My2.Text.Trim() + "', 'yyyy-mm-dd ') ";
                if (txtColor.Text.Trim() != "")
                    sqlwhere += " and lower(r.color) like lower('%" + txtColor.Text.Trim() + "%') ";
                if (ddlResult.SelectedValue != "")
                    sqlwhere += " and lower(FINALRESULT)=lower('" + ddlResult.SelectedValue.Trim() + "') and a.status=7 ";
                if (txtSuppliername.Text.Trim() != "")
                    sqlwhere += " and lower(s.suppliername) like lower('%" + txtSuppliername.Text.Trim() + "%') ";
                if (txtSuppliercode.Text.Trim() != "")
                    sqlwhere += " and lower(s.suppliercode) like lower('%" + txtSuppliercode.Text.Trim() + "%') ";
                if (txtPPARNO.Text.Trim() != "")
                    sqlwhere += " and lower('PPAR-'||a.pparno||'.'||PPARVERSION) like lower('%" + txtPPARNO.Text.Trim() + "%') ";
            }
            if (CurrentUser.UnitId == "99")
                sqlwhere += " and p.supplieradmin='" + CurrentUser.Id + "'";
            if (CurrentUser.UnitId == "0")
                sqlwhere += " and r.plantid=" + CurrentUser.UnitName;
            if (chkMycase.Checked)
            {
                sqlwhere += " and  (u.superior='" + CurrentUser.Id + "' or u.superior1='" + CurrentUser.Id + "' or u.superior2='" + CurrentUser.Id + "'  or (a.QuanlityEngineer='" + CurrentUser.Id + "'  or a.quanlityengineer='" + CurrentUser.Id + "' or a.quanlitymanager='" + CurrentUser.Id + "' or a.quanlityvp='" + CurrentUser.Id + "' or a.qeuser='" + CurrentUser.Id + "'  or a.id in (select pparid from samplecard where DEPTREP='" + CurrentUser.Id + "') ) )";
            }
            sqlwhere += " and a.status!=9 ";

            sqlwhere+=@"  group by a.id,r.bdntpartno,r.bdntpartname,r.color,s.suppliercode,'PPAR-'||a.pparno||'.'||PPARVERSION ,PPARVERSION,a.elevel||a.qlevel ,r.bdntrevisionno ,si.receivedate,a.planedppardate,a.status,a.endtime,FINALRESULT,a.qeuser,r.bdntrevisionstatus,a.status,a.decisiontext,a.explanations,
a.resubmissiondate,a.DEVIATIONEXPIREDATE,s.dsc,s.contacttel,remarks,SUPPLIERPARTNO,a.FINALSTATUS,a.isinapp,s.suppliername,p.plantname,p.supplieradmin,ppardate ";

            sqlwhere += sort;
            DataSet ds = bo.GetListForWhere2(sqlwhere);
            return ds;
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            //btnSubmit_Click(null, null);
            BindGridView();
        }

        /// <summary>
        /// Export
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {

                DataSet ds = GetDataSet("");
                //ds.Tables[0].Columns.Add("ShowStatus");
                foreach (DataRow r in ds.Tables[0].Rows)
                {
                    if(CurrentUser.UnitId=="0"||CurrentUser.UnitId=="99")
                    r["ShowStatus"] = ShowAuditStatus2(r["status"].ToString(),r["isinapp"].ToString());
                    else
                        r["ShowStatus"] = ShowAuditStatus(r["status"].ToString(),r["FINALSTATUS"].ToString(),r["isinapp"].ToString());
                    r["d1"] = r["PPARDATE"].ToString() == "" ? r["PPARDATE"] : DateTime.Parse(r["PPARDATE"].ToString()).ToString("yyyy-MM-dd");
                    r["d2"] = r["ENDTIME"].ToString() == "" ? r["ENDTIME"] : DateTime.Parse(r["ENDTIME"].ToString()).ToString("yyyy-MM-dd");
                    r["d4"] = r["receivedate"].ToString() == "" ? r["receivedate"] : DateTime.Parse(r["receivedate"].ToString()).ToString("yyyy-MM-dd");
                    r["d3"] = DateTime.Parse(r["planedppardate"].ToString()).ToString("yyyy-MM-dd");
                    r["d5"] = r["resubmissiondate"].ToString() == "" ? r["resubmissiondate"] : DateTime.Parse(r["resubmissiondate"].ToString()) == DateTime.Parse("1900-01-01") ? "" : DateTime.Parse(r["resubmissiondate"].ToString()).ToString("yyyy-MM-dd");
                    r["d6"] = r["pd"].ToString() == "" ? r["pd"] : DateTime.Parse(r["pd"].ToString()) == DateTime.Parse("1900-01-01") ? "" : DateTime.Parse(r["pd"].ToString()).ToString("yyyy-MM-dd");
                }
                ds.Tables[0].Columns.Remove("ID");
                ds.Tables[0].Columns.Remove("BDNTREVISIONSTATUS");
                ds.Tables[0].Columns.Remove("STATUS");
                ds.Tables[0].Columns.Remove("DECISIONTEXT");
                ds.Tables[0].Columns.Remove("EXPLANATIONS");
                ds.Tables[0].Columns.Remove("RESUBMISSIONDATE");
                ds.Tables[0].Columns.Remove("DEVIATIONEXPIREDATE");
                ds.Tables[0].Columns.Remove("DSC");
                ds.Tables[0].Columns.Remove("CONTACTTEL");
                //ds.Tables[0].Columns.Remove("ADDRESS");
                ds.Tables[0].Columns.Remove("planedppardate");
                //ds.Tables[0].Columns.Remove("SUPPLIERCODE");
               // ds.Tables[0].Columns.Remove("PPARNO1");
                ds.Tables[0].Columns.Remove("PPARVERSION");
                ds.Tables[0].Columns.Remove("SUPPLIERPARTNO");
               // ds.Tables[0].Columns.Remove("BDNTREVISIONNO");
                //ds.Tables[0].Columns.Remove("SUPPLIERNAME");
                ds.Tables[0].Columns.Remove("REMARKS");
                ds.Tables[0].Columns.Remove("PPARDATE");
                ds.Tables[0].Columns.Remove("pd");
                ds.Tables[0].Columns.Remove("ENDTIME");
                ds.Tables[0].Columns.Remove("FINALSTATUS");
                ds.Tables[0].Columns.Remove("isinapp");
                ds.Tables[0].Columns.Remove("receivedate");
              //  ds.Tables[0].Columns.Remove("resubmissiondate");


                ds.Tables[0].Columns["ROWNUM"].ColumnName = "SN";
                ds.Tables[0].Columns["BDNTPARTNO"].ColumnName = "Part number";
                ds.Tables[0].Columns["BDNTPARTNAME"].ColumnName = "Part name";
                ds.Tables[0].Columns["COLOR"].ColumnName = "Color";
                ds.Tables[0].Columns["PPARNO"].ColumnName = "PPAR";
                //ds.Tables[0].Columns["PPARVERSION"].ColumnName = "PPAR version";
                ds.Tables[0].Columns["d1"].ColumnName = "Sample Card Start date";
                ds.Tables[0].Columns["d2"].ColumnName = "PPAR End date";
                ds.Tables[0].Columns["d3"].ColumnName = "Planned PPAR date";
                ds.Tables[0].Columns["FINALRESULT"].ColumnName = "Result";
                ds.Tables[0].Columns["QEUSER"].ColumnName = "BDNT Q-engineer";
                ds.Tables[0].Columns["QLEVEL"].ColumnName = "Q-level";
                ds.Tables[0].Columns["SHOWSTATUS"].ColumnName = "Status";
                ds.Tables[0].Columns["BDNTREVISIONNO"].ColumnName = "Revision";
                ds.Tables[0].Columns["suppliercode"].ColumnName = "Supplier code";
                ds.Tables[0].Columns["d4"].ColumnName = "Part receiving date";
                ds.Tables[0].Columns["suppliername"].ColumnName = "Supplier name";
                ds.Tables[0].Columns["address"].ColumnName = "Manufacturing location";
                ds.Tables[0].Columns["supplieradmin"].ColumnName = "Supplier admin";
                ds.Tables[0].Columns["d5"].ColumnName = "re-submission date";
                ds.Tables[0].Columns["d6"].ColumnName = "PPAR Start date";
                CreateExcel(ds, "PPARHistory");
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void dgList_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();
            
            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.dgList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.dgList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            this.dgList.Attributes["SortExpression"] = sortExpression;
            this.dgList.Attributes["SortDirection"] = sortDirection;
            

            string pic="";
            pic = sortDirection == "ASC" ? "<img src='../Images/icon/arrowup.gif' />" : "<img src='../Images/icon/arrowdown.gif' />";
                
            foreach (DataGridColumn item in dgList.Columns)
            {
                if (item.SortExpression == sortExpression)
                {
                    item.HeaderText = item.FooterText + " " + pic;
                }
                else
                    item.HeaderText = item.FooterText;
            }

            this.BindGridView();
            
        }

        private void BindGridView()
        {
           
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.dgList.Attributes["SortExpression"];
            string sortDirection = this.dgList.Attributes["SortDirection"];
            if (sortExpression != null)
            {
                // 调用业务数据获取方法
                string sort = string.Format("  order by lower({0})  {1} ", sortExpression, sortDirection);
                if (sortExpression == "ppardate" || sortExpression == "endtime" || sortExpression == "planedppardate"||sortExpression=="receivedate")
                {
                    sort = string.Format("  order by {0}  {1} ", sortExpression, sortDirection);
                }
                DataTable dtBind = GetDataSet(sort).Tables[0];
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    dtBind.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                // GridView绑定并显示数据
                this.dgList.DataSource = GetPageTable(dtBind, AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
                this.dgList.DataBind();
            }
            else
                btnSubmit_Click(null, null);
        }
    }
}